package com.example.interactservice.serviceImpl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.commom.enums.StatusCodeEnum;
import com.example.commom.exception.CustomException;
import com.example.commom.utils.JwtUtils;
import com.example.feign.result.AjaxResult;
import com.example.interactservice.entity.BookReviewsBranch;
import com.example.interactservice.entity.BookReviewsRoot;
import com.example.interactservice.mapper.BookReviewsRootMapper;
import com.example.interactservice.service.BookReviewsBranchService;
import com.example.interactservice.service.BookReviewsRootService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 软工2104-李家强-2100770248
 * @since 2023-09-21
 */
@Service
@Transactional
public class BookReviewsRootServiceImpl extends ServiceImpl<BookReviewsRootMapper, BookReviewsRoot> implements BookReviewsRootService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BookReviewsBranchService bookReviewsBranchService;

    @Autowired
    private BookReviewsRootService bookReviewsRootService;


    /**
     *  通过 id 获取 子评论信息
     * @param bookReviewsRootId 子评论 id
     * @return 子评论对象
     */
    @Override
    public BookReviewsRoot getReviewById(Long bookReviewsRootId, String userId) {
        BookReviewsRoot result = getById(bookReviewsRootId);

        if (result == null) {
            return null;
        }

        this.isReviewLiked(result, userId);
        return result;
    }

    /**
     *  获取指定书籍指定章节的主评论
     * @param targetBook 书籍id
     * @param targetChapter 章节id
     * @return 评论集合
     */
    @Override
    public List<BookReviewsRoot> getAllReviews(Long targetBook,Long targetChapter, String userId) {
        LambdaUpdateWrapper<BookReviewsRoot> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(BookReviewsRoot::getBookId, targetBook)
                .eq(BookReviewsRoot::getChapterId, targetChapter)
                .orderByDesc(BookReviewsRoot::getPrizeCount);

        List<BookReviewsRoot> result = bookReviewsRootService.list(lambdaUpdateWrapper);

        result.forEach(item -> {
            this.isReviewLiked(item, userId);
        });

        return result;
    }


    /**
     *  插入一条主评论
     */
    @Override
    public boolean insertRootReview(BookReviewsRoot bookReviewsRoot) {

        bookReviewsRoot.setReviewId(null);

        boolean success = bookReviewsRootService.save(bookReviewsRoot);
        if (success) {
            return true;
        } else {
            throw new CustomException(StatusCodeEnum.FAILED.getMsg(), -1);
        }
    }

    /**
     *  删除一条主评论
     */
    @Override
    public boolean deleteRootReview(Long targetId) {
        // 1. 删除主评论
        boolean remove = bookReviewsRootService.removeById(targetId);

        if (remove) {
            // 2. 删除子评论
            LambdaUpdateWrapper<BookReviewsBranch> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(BookReviewsBranch::getReviewRootId, targetId);
            boolean success = bookReviewsBranchService.remove(lambdaUpdateWrapper);
            if (success) {
                return true;
            } else {
                throw new CustomException(StatusCodeEnum.FAILED.getMsg(), -1);
            }
        } else {
            throw new CustomException(StatusCodeEnum.FAILED.getMsg(), -1);
        }
    }


    /**
     *  用户点赞/取消点赞
     * @param targetId 评论 id
     * @param token token 验证信息
     * @return 结果
     */
    @Override
    public AjaxResult likeReview(Long targetId, String token) {
        // 1. 拿到登录用户的id
        String userIdByToken = JwtUtils.getUserIdByToken(token);
        if (userIdByToken == null) {
            return AjaxResult.fail(StatusCodeEnum.Redirect.getCode(), StatusCodeEnum.Redirect.getMsg());
        }

        String key = "reviewRoot:like:" + targetId;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userIdByToken);

        // 2. 判断当前用户是否已经点赞
        if (BooleanUtil.isFalse(isMember)) {
            // 3. 未点赞, 就可以点赞
            // 3.1 点赞数目 +1
            boolean success = update().setSql("prize_count = prize_count + 1")
                    .eq("review_id", targetId).update();

            if (success) {
                // 3.2 将用户保存到 redis 的 set 集合中.
                stringRedisTemplate.opsForSet().add(key, userIdByToken);
            }
        } else {
            // 4. 已经点赞, 那就是取消点赞
            boolean success = update().setSql("prize_count = prize_count - 1")
                    .eq("review_id", targetId).update();

            if (success) {
                // 3.2 将用户从 redis 的 set 集合中移除.
                stringRedisTemplate.opsForSet().remove(key, userIdByToken);
            }
        }

        return AjaxResult.success(StatusCodeEnum.OK.getMsg());
    }


    /**
     *  判断评论是否已经被点赞
     */
    private void isReviewLiked(BookReviewsRoot bookReviewsRoot, String userId) {
        // 默认必须登录才能调用这个接口

        // 判断当前用户是否已经点赞
        String key = "reviewRoot:like:" + bookReviewsRoot.getReviewId();
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId);

        bookReviewsRoot.setLike(BooleanUtil.isTrue(isMember));

    }
}
